package com.pp.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pp.common.pojo.Comment;
import com.pp.common.pojo.Post;
import com.pp.common.pojo.User;
import com.pp.web.mapper.CommentMapper;
import com.pp.web.mapper.PostMapper;
import com.pp.web.model.dto.CreateCommentDTO;
import com.pp.web.model.vo.CommentVO;
import com.pp.web.service.ICommentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Resource
    private PostMapper postMapper;

    @Override
    public List<CommentVO> getCommentsByPostId(String postId) {
        List<CommentVO> comments = this.baseMapper.findCommentsByPostId(postId);
        Assert.notNull(comments, "获取评论列表失败");
        return comments;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Comment createComment(CreateCommentDTO createCommentDTO, User user) {
        // 构建 newComment 对象
        Comment newComment = Comment.builder()
                                 .postId(createCommentDTO.getPostId())
                                 .userId(user.getId())
                                 .commentContent(createCommentDTO.getCommentContent())
                                 .createdUser(user.getUsername())
                                 .updatedUser(user.getUsername())
                                 .build();

        // 将 newComment 对象入库
        this.baseMapper.insert(newComment);

        // 添加新评论成功后，更新帖子 commentNum 信息
        // 每添加一评论，帖子的评论量 + 1
        Post post = postMapper.selectById(createCommentDTO.getPostId());
        int newCommentNum = post.getCommentNum() + 1;
        post.setCommentNum(newCommentNum);
        postMapper.updateById(post);

        // 返回入库的 newComment 对象
        return newComment;
    }
}
